package com.superzlc.vcontroller.message.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.util.Log;

import com.superzlc.vcontroller.message.client.MessageOp.DataPackage;

public class MessageClient {
	static final String TAG = "MessageClient";

	private String ip;
	private int port;
	private Socket socket;

	private OutputStream os;
	private InputStream is;
//	private DataOutputStream dos;
//	private DataInputStream dis;

	private boolean isStarted;

	public MessageClient(String ip, int port) {
		this.ip = ip;
		this.port = port;
		socket = new Socket();
	}

	public boolean isStarted() {
		return isStarted;
	}

	public void startup() {
		try {
			socket.connect(new InetSocketAddress(ip, port), Constants.CONNECT_TIMEOUT_MS);
		} catch (IOException e1) {
			Log.i(TAG, "连接到" + ip + ":" + port + "失败");
			e1.printStackTrace();
		}
		try {
			os = socket.getOutputStream();
			is = socket.getInputStream();
//			dos = new DataOutputStream(os);
//			dis = new DataInputStream (is);
		} catch (IOException e1) {
			Log.i(TAG, "获取socket流失败");
			e1.printStackTrace();
		}

		new Thread(){
			public void run() {
				try {
					readLoop();
				} catch (IOException | InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();

		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
			return;
		}

		isStarted = true;

//		new Thread(){
//			public void run() {
//				try {
//					sendHeardbeatLoop();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		}.start();
	}

	public void shutdown() {
		isStarted = false;
		if (this.is != null) {
			try {
				is.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		if (this.os != null) {
			try {
				os.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		if (socket != null && !socket.isClosed()) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void finalize() {
		this.shutdown();
	}

	//
	private void readLoop() throws IOException, InterruptedException {
		byte[] buffer = new byte[1024 * 10];
		while(isStarted) {
			DataPackage p = MessageOp.read(is, buffer);
			System.out.println("接收到" + p.toString());
		}
	}

	public void sendHeardbeat() throws IOException {
		if (isStarted)
			MessageOp.sendHeardbeat(os);
	}

//	long lasttimeOfWrite;
//	public void sendHeardbeatLoop() throws Exception {
//		while(true) {
//			synchronized(dos) {
//				if (System.currentTimeMillis() - lasttimeOfWrite > 1000 * 3)
//					MessageOp.sendHeardbeat(dos);
//			}
//			Thread.sleep(1000 * 3);
//		}
//	}

	public void sendData(DataPackage pkg) throws IOException {
//		synchronized(dos) {
		if (isStarted)
			MessageOp.sendData(os, pkg);
//			lasttimeOfWrite = System.currentTimeMillis();
//		}
	}
}
